package com.ruoyi.system.service.impl;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.ILuntaiStoreApplicationService;

/**
 * 门店申请记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-17
 */
@Service
public class LuntaiStoreApplicationServiceImpl implements ILuntaiStoreApplicationService {
    @Autowired
    private LuntaiStoreApplicationMapper luntaiStoreApplicationMapper;

    @Autowired
    private LuntaiUserMapper luntaiUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    @Autowired
    private LuntaiStoreMapper luntaiStoreMapper;

    @Value("${url.pc}")
    public String webUrl;

    @Autowired
    private LuntaiMessageMapper luntaiMessageMapper;

    /**
     * 查询门店申请记录
     *
     * @param id 门店申请记录主键
     * @return 门店申请记录
     */
    @Override
    public LuntaiStoreApplication selectLuntaiStoreApplicationById(Integer id) {
        return luntaiStoreApplicationMapper.selectLuntaiStoreApplicationById(id);
    }

    /**
     * 查询门店申请记录列表
     *
     * @param luntaiStoreApplication 门店申请记录
     * @return 门店申请记录
     */
    @Override
    public List<LuntaiStoreApplication> selectLuntaiStoreApplicationList(LuntaiStoreApplication luntaiStoreApplication) {
        return luntaiStoreApplicationMapper.selectLuntaiStoreApplicationList(luntaiStoreApplication);
    }

    /**
     * 新增门店申请记录
     *
     * @param luntaiStoreApplication 门店申请记录
     * @return 结果
     */
    @Override
    public int insertLuntaiStoreApplication(LuntaiStoreApplication luntaiStoreApplication) {
        luntaiStoreApplication.setCreateTime(DateUtils.getNowDate());
        return luntaiStoreApplicationMapper.insertLuntaiStoreApplication(luntaiStoreApplication);
    }


    /**
     * 修改门店申请记录
     *
     * @param luntaiStoreApplication 门店申请记录
     * @return 结果
     */
    @Override
    public int updateLuntaiStoreApplication(LuntaiStoreApplication luntaiStoreApplication) {
        Integer status = luntaiStoreApplication.getStatus();
        if (status != null) {
            if (status == 1) {
                generateAdminAndStore(luntaiStoreApplication);
            }
            if (status != 0) {
                sendMessage(luntaiStoreApplication);
            }
        }
        return luntaiStoreApplicationMapper.updateLuntaiStoreApplication(luntaiStoreApplication);
    }


    public void generateAdminAndStore(LuntaiStoreApplication luntaiStoreApplication) {
        // 获取申请信息
        LuntaiStoreApplication applicationInfo = luntaiStoreApplicationMapper.selectLuntaiStoreApplicationById(luntaiStoreApplication.getId());
        Integer userId = applicationInfo.getUserId();

        // 获取用户信息
        LuntaiUser luntaiUser = luntaiUserMapper.selectLuntaiUserById(userId);
        if (luntaiUser == null) {
            throw new IllegalArgumentException("用户信息不存在");
        }

        // 设置用户备注为门店管理员
        luntaiUser.setRemark(applicationInfo.getStoreName() + "门店管理员");
        luntaiUser.setRole(3);
        luntaiUserMapper.updateLuntaiUser(luntaiUser);

        // 校验是否已存在该管理员账号
        SysUser sysUser1 = sysUserMapper.selectUserByUserName(luntaiUser.getUsername());
        if (sysUser1 != null) {
            throw new IllegalArgumentException("此管理员账号已存在或重名");
        }


        // 创建管理员账号
        SysUser sysUser = new SysUser();
        sysUser.setUserName(luntaiUser.getUsername());
        sysUser.setPassword(SecurityUtils.encryptPassword(luntaiUser.getPhone()));
        sysUser.setNickName(applicationInfo.getStoreName() + "门店");
        sysUser.setPhonenumber(luntaiUser.getPhone());
        sysUser.setAvatar(luntaiUser.getIcon());
        sysUser.setCreateBy(SecurityUtils.getUsername());
        sysUser.setRemark("门店管理员");
        sysUserMapper.insertUser(sysUser);
        // 创建门店信息
        LuntaiStore luntaiStore = new LuntaiStore();
        luntaiStore.setCreateTime(DateUtils.getNowDate());
        luntaiStore.setAdminId(Math.toIntExact(sysUser.getUserId()));
        luntaiStore.setAdminPhone(luntaiUser.getPhone());
        luntaiStore.setName(applicationInfo.getStoreName());
        luntaiStore.setAddress(applicationInfo.getAddress());
        luntaiStore.setCity(applicationInfo.getCity());
        luntaiStore.setProvince(applicationInfo.getProvince());
        luntaiStore.setLatitude(applicationInfo.getLatitude());
        luntaiStore.setLongitude(applicationInfo.getLongitude());
        luntaiStore.setPhone(applicationInfo.getPhone());
        luntaiStore.setCover(applicationInfo.getCover());
        luntaiStore.setLicense(applicationInfo.getLicense());
        luntaiStoreMapper.insertLuntaiStore(luntaiStore);
    }

    public void sendMessage(LuntaiStoreApplication luntaiStoreApplication) {
        LuntaiStoreApplication applicationInfo = luntaiStoreApplicationMapper.selectLuntaiStoreApplicationById(luntaiStoreApplication.getId());
        String message = "消息内容";

        // 根据状态设置消息内容
        switch (luntaiStoreApplication.getStatus()) {

            case 1:
                message = "您申请的门店 " + applicationInfo.getStoreName() + " 已审批通过,管理员账号密码为您当前手机号";

                break;
            case 2:
                message = "您申请的门店 " + applicationInfo.getStoreName() + " 审批不通过,请核查后重新申请";
                break;
        }

        // 创建消息对象并保存
        Integer userId = applicationInfo.getUserId();
        LuntaiMessage luntaiMessage = new LuntaiMessage();
        luntaiMessage.setType(1);
        luntaiMessage.setTitle(message);
        luntaiMessage.setInfo(message);
        luntaiMessage.setUserId(userId);
        luntaiMessage.setIsread(0);
        luntaiMessage.setIsdelete(0);
        luntaiMessageMapper.insertLuntaiMessage(luntaiMessage);// 获取用户信息
        LuntaiUser luntaiUser = luntaiUserMapper.selectLuntaiUserById(applicationInfo.getUserId());
        sendAuditResult(luntaiStoreApplication.getStatus(), luntaiUser.getOpneid());

    }

    public void sendAuditResult(Integer type, String openId) {
        String passContent = "{\n" +
                "  \"openId\": \"" + openId + "\",\n" +  // 动态赋值
                "  \"result\": \"已通过\",\n" +
                "  \"auditType\": \"门店申请\",\n" +
                "  \"remake\": \"打开小程序查看站内信消息\"\n" +
                "}";

        String refuseContent = "{\n" +
                "  \"openId\": \"" + openId + "\",\n" +  // 动态赋值
                "  \"result\": \"已拒绝\",\n" +
                "  \"auditType\": \"门店申请\",\n" +
                "  \"remake\": \"打开小程序查看拒绝理由\"\n" +
                "}";
        String info = passContent;
        switch (type) {
            case 1:
                info = passContent;
                break;
            case 2:
                info = refuseContent;
                break;
        }
        String url = webUrl + "luntai/sendAuditResult";
        try {
            // 创建 URL 对象
            URL endpoint = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
            // 设置请求方法和头信息
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
            // 写入 JSON 数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = info.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("响应码: " + responseCode);
            // 读取响应内容（可选）
            if (responseCode >= 200 && responseCode < 300) {
                System.out.println("请求成功！");
            } else {
                System.out.println("请求失败，响应码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送请求时发生错误，请检查 URL 和网络连接。");
        }
    }

    /**
     * 批量删除门店申请记录
     *
     * @param ids 需要删除的门店申请记录主键
     * @return 结果
     */
    @Override
    public int deleteLuntaiStoreApplicationByIds(Integer[] ids) {
        return luntaiStoreApplicationMapper.deleteLuntaiStoreApplicationByIds(ids);
    }

    /**
     * 删除门店申请记录信息
     *
     * @param id 门店申请记录主键
     * @return 结果
     */
    @Override
    public int deleteLuntaiStoreApplicationById(Integer id) {
        return luntaiStoreApplicationMapper.deleteLuntaiStoreApplicationById(id);
    }

    @Override
    public boolean getAuditStatus(Integer type) {
        Integer result = luntaiStoreApplicationMapper.getAuditStatus(type);
        return result.equals(1);
    }

    @Override
    public void updateAuditStatus(Integer type) {
        luntaiStoreApplicationMapper.updateAuditStatus(type);
    }


}
